package 线程安全.多线程;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class FIleUpload_Server {
    public static void main(String[] args) throws IOException {
        System.out.println("server is up!");
        ServerSocket ssk = new ServerSocket(6666);

        while (true) {
            Socket accept = ssk.accept();
            new Thread(() -> {
                try {
                    BufferedInputStream bis = new BufferedInputStream(accept.getInputStream());
                    FileOutputStream fos = new FileOutputStream(System.currentTimeMillis() + ".jpg");
                    BufferedOutputStream bos = new BufferedOutputStream(fos);

                    byte[] bytes = new byte[1024 * 8];
                    int len = 0;
                    while ((len = bis.read(bytes)) != -1) {
                        bos.write(bytes, 0, len);
                    }

                    System.out.println("msg back!");

                    OutputStream outputStream = accept.getOutputStream();
                    outputStream.write("上传成功".getBytes());
                    outputStream.close();

                    bos.close();
                    bis.close();
                    accept.close();
                    System.out.println("文件上传已保存！");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
    }
}
